package com.yushu.common.util.string;

 /**
 * 驼峰转换类
 * @author test
 * @CreateDate 2020-12-03 15:47:24
 */
public class CamelCaseUtil {

    /**
     * 转换成下划线式的字符串
     *
     * @param s
     * @return
     */
    public static String toUnderlineName(String s) {
        if (s == null) {
            return null;
        } else if (!org.apache.commons.lang3.StringUtils.isAllUpperCase(s) && !org.apache.commons.lang3.StringUtils.isAllLowerCase(s)) {
            StringBuilder sb = new StringBuilder();
            boolean upperCase = false;

            for (int i = 0; i < s.length(); ++i) {
                char c = s.charAt(i);
                char nextC = ' ';
                char lastC = ' ';
                boolean nextUpperCase = true;
                if (i < s.length() - 1) {
                    nextC = s.charAt(i + 1);
                    nextUpperCase = Character.isUpperCase(nextC);
                    if (i > 0) {
                        lastC = s.charAt(i - 1);
                    }
                }

                if (i >= 0 && Character.isUpperCase(c)) {
                    if ((!upperCase && lastC != '_'/* || !nextUpperCase */) && i > 0 && nextC != '_') {
                        sb.append('_');
                    }

                    upperCase = true;
                } else {
                    upperCase = false;
                }

                sb.append(Character.toUpperCase(c));
            }

            return sb.toString();
        } else {
            return s;
        }
    }


    public static String toCamelCase(String s) {
        if (s == null) {
            return null;
        } else {
            s = s.toLowerCase();
            StringBuilder sb = new StringBuilder(s.length());
            boolean upperCase = false;

            for (int i = 0; i < s.length(); ++i) {
                char c = s.charAt(i);
                if (c == '_') {
                    upperCase = true;
                } else if (upperCase) {
                    sb.append(Character.toUpperCase(c));
                    upperCase = false;
                } else {
                    sb.append(c);
                }
            }

            return sb.toString();
        }
    }
}
